﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using FirstFloor.ModernUI.Windows.Controls;
using IsikFx.Project.CommonTypes.Fund;
using IsikFx.Project.CommonTypes.User;
namespace IsikFx.Project.MainApp.Pages
{
    /// <summary>
    /// Interaction logic for Home.xaml
    /// </summary>
    public partial class Home : UserControl
    {
        Timer timer = new Timer();
        public static bool animationCompleted = true;

        List<string> photoFileNames = new List<string>();

        public static readonly RoutedEvent NewFundEvent = EventManager.RegisterRoutedEvent("NewFundEvent", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(Home));

        public event RoutedEventHandler NewFund
        {
            add { AddHandler(NewFundEvent, value); }
            remove { RemoveHandler(NewFundEvent, value); }
        }
        public static object lockObj = new object();

        public Home()
        {
            InitializeComponent();
            Loaded += Home_Loaded;
            timer.Interval = double.Parse(System.Configuration.ConfigurationManager.AppSettings["NewFundRequestInterval"]);
            timer.Enabled = true;
            timer.Elapsed += timer_Elapsed;
            InitializeUsersList();
            story.Completed += story_Completed;
        }

        void story_Completed(object sender, EventArgs e)
        {
            animationCompleted = true;
        }


        void Home_Loaded(object sender, RoutedEventArgs e)
        {
            CheckForNewFund();
            RaiseEvent(new RoutedEventArgs { RoutedEvent = NewFundEvent });
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Dispatcher.Invoke(new Action(CheckForNewFund), System.Windows.Threading.DispatcherPriority.Normal);
        }

        private void InitializeUsersList()
        {
            try
            {
                IsikFxWcfService.ServiceClient client = new IsikFxWcfService.ServiceClient();
                UserResponseMessage responseMessage = client.GetUsersByRole(1);
                if (responseMessage != null)
                {
                    if (responseMessage.Response != null && responseMessage.Response.User != null && responseMessage.Response.User.Count > 0)
                    {
                        List<User> list = responseMessage.Response.User;

                        foreach (User _user in list)
                        {
                            string fileNamePrefix = string.Format("{0}_{1}", _user.Name, _user.Surname);
                            string tempPath = System.IO.Path.GetTempPath();
                            string directory = System.Configuration.ConfigurationManager.AppSettings["PhotoFilePath"] as string;
                            string fullPath = System.IO.Path.Combine(tempPath, directory);
                            if (!Directory.Exists(directory))
                                Directory.CreateDirectory(directory);
                            List<string> files = Directory.GetFiles(directory).ToList();
                            _user.DisplayName = string.Format("{0} {1}", _user.Name, _user.Surname);
                            foreach (string fileName in files)
                            {
                                if (fileName.Contains(fileNamePrefix))
                                {
                                    _user.PhotoPath = fileName;
                                    break;
                                }
                                else
                                    _user.PhotoPath = string.Empty;
                            }
                        }
                        list.Sort(new UserComparer());
                        list.Reverse();
                        usersList.ItemsSource = list;
                    }
                }
            }
            catch (Exception ex)
            {
                ModernDialog dialog = new ModernDialog();
                dialog.Content = "Listeye şu an ulaşılamıyor. :(";
                dialog.Title = "Hata";
                dialog.Show();
            }
        }

        public void CheckForNewFund()
        {
            if (animationCompleted)
            {
                IsikFxWcfService.ServiceClient client = new IsikFxWcfService.ServiceClient();
                FundResponseMessage funds = client.GetNewFunds();
                if (!funds.HasError)
                {
                    if (funds.Response != null && funds.Response.Funds != null && funds.Response.Funds.Count > 0)
                    {
                        List<Fund> newFund = funds.Response.Funds;
                        foreach (Fund fund in newFund)
                        {
                            this.DataContext = fund;
                            client.UpdateFundShownStatus(fund.ID);
                            animationCompleted = false;
                            story.Begin();
                            InitializeUsersList();
                            break;
                        }
                    }
                }
            }
        }
    }

    public class UserComparer : IComparer<User>
    {
        public int Compare(User x, User y)
        {
            decimal amount1 = decimal.TryParse(x.TotalFundAmount, out amount1) ? amount1 : decimal.Zero;
            decimal amount2 = decimal.TryParse(y.TotalFundAmount, out amount2) ? amount2 : decimal.Zero;
            return amount1.CompareTo(amount2);
        }
    }
}
